<?php

class MyOrderController extends CenterController {

	protected $orderService;

	public function __construct(OrderService $orderService)
	{
		parent::__construct();
		$this->orderService = $orderService;
	}
	/**
	 * 提交小薇企服订单
	 */
	public function submitOrder()
	{
			$input = Input::all();
			$rules = array(
					'product_id' => 'required|exists:product,id',
					'email' => 'required|email',
					'company_name' => 'required',
					'province' => 'required',
					'city' => 'required',
					'district' => 'required',
					'memo' => 'between:0,60'
				);
			$messages = array(
					'product_id.required' => '请提交产品id',
					'product_id.exists' => '该产品不存在',
					'email.required' => '请填写联系人邮箱',
					'email.email' => '邮箱格式不正确',
					'company_name.required' => '请填写企业名称',
					'city.required' => '请选择企业所在市',
					'district.required' => '请选择企业联系所在省',
					'province.required' => '请选择企业联系所在区',
					'memo.between' => '备注在60字以内'
					
				);
			$validator = Validator::make($input, $rules, $messages);
			if($validator->fails()){
				return $this->makeView('errors.400', $validator->errors(), 400);
			}
			try{
				$output = DB::transaction(function($input) use ($input)
			{
					$product = Product::find($input['product_id']);
					$qty = ($product->id == 1)? 2:1;
					$order_model = App::make('Order');
					$order_model->user_id =Auth::user()->id;
					$order_model->price =$product->price * $qty;
					$order_model->qty = $qty;
					// $order_model->phone = $input['contact_phone'];
					// $order_model->memo = $input['memo'];
					$order_model->memo = isset($input['memo'])?$input['memo']:"";
			                        $order_model->workflow_id = 0;
			                        $order_model->pay_status = 0;
					$order_model->state = Order::STATE_INIT;
					$order_model->title = $product->name;
					$order_model->save();
					$data = array(
								'title' => $product->name,
								'type' => Post::TYPE_PAY_COMPANY
							);
					$new_post = Post::storePayQuestion($data);
					$new_post->assignToOrder($order_model->id);
					$input['order_id'] = $order_model->id;
					$new_company = CompanyServer::_create($input);
				            $work_flow = App::make('Workflow');
				            $work_flow->order_id = $order_model->id;
				            $work_flow->workflow_node_id = WorkflowNode::where('act_order', 1)->pluck('id');
				            $work_flow->user_id = Auth::user()->id;
				            $work_flow->user_name = Auth::user()->realname?Auth::user()->realname:Auth::user()->id;
				            $work_flow->memo = '';
				            $work_flow->save();
                    
					// 保存order item

					$product = App::make('Product')->find($input['product_id']);
					$order_item_model = App::make('OrderItem');
					$order_item_model->order_id = $order_model->id;
					$order_item_model->product_id = $input['product_id'];
					$order_item_model->price = $product->price;
					$order_item_model->qty = $qty;
					$order_item_model->save();
					return array('order'=>$order_model->toArray(), 'post' => $new_post->toArray());
			});
			
		}catch (Exception $ex) {
			Log::error($ex);
			return $this->makeView('errors.503','服务器暂时无法响应，请稍后再试',503);
		}
		
		return $this->makeView('general.200', $output, 200);		
	}

	/*
	 * 付费咨询
	 */
	// public function create() {


	// 	if (Input::server ( 'REQUEST_METHOD' ) == 'POST') {
	// 		$post = Input::all();
				
	// 		$rules = array (
	// 				'title' => 'required',
	// 				'content' => 'required|between:2,1000',
	// 				'cat_id' => 'required',
	// 				'file_paths' => 'array',
	// 				'type' => 'required|in:5,6',
	// 				'lawyer_id' => 'required|exists:lawyer,user_id'
	// 		);
	// 		$messages = array(
	// 				'title.required' => '请填写咨询标题',
	// 				'content.required' => '请填写咨询内容',
	// 				'cat_id.required' => '请选择法律类别',
	// 				'file_paths.array' => '上传的文件列表要是数组的格式',
	// 				'content.between' => '咨询内容长度在:min到:max之间',
	// 				'type.required' => '请选择咨询类型',
	// 				'type.in' => '咨询类型错误',
	// 				'lawyer_id.required' => '请提交律师id',
	// 				'lawyer_id.exists' => '该律师不存在'
	// 		);
				
	// 		$validator = Validator::make ( $post, $rules, $messages );
	// 		if ($validator->fails()) {
	// 			// the given data did not pass validation
	// 			return $this->makeView(
	// 					'errors.400',
	// 					$validator->errors(),
	// 					400
	// 			);
	// 		}
	// 		try {
	// 			// 保存咨询
	// 			$post = UtilsHelper::filter_sensitive_word($post);   //敏感词过滤
	// 			$post['post_category'] = $post['cat_id'];
	// 			$new_post = Post::storePayQuestion($post);
	// 			$new_post->load('postExtra', 'comments');
	// 			$lawyer = Lawyer::find($post['lawyer_id']);
	// 			$price = '';
	// 			if($new_post->type == Post::TYPE_PAY_TEXT){
	// 				$price = $lawyer->text_reply_fee;
	// 			}
	// 			if($new_post->type == Post::TYPE_PAY_PHONE){
	// 				$price = $lawyer->phone_reply_fee;
	// 			}
	// 			$order = new Order();
	// 			$order->user_id = Auth::user()->id;
	// 			$order->price =$price;
	// 			$order->title = $post['title'];
	// 			$order->phone = isset($post['phone'])?$post['phone']:Auth::user()->phone;
	// 			$order->qty = 1;
	// 			$order->workflow_id = 0;
	// 			$order->state = Order::STATE_INIT;
	// 			$order->pay_status = 0;
	// 			$order->save();
	// 			$new_post->assignToLawyer($lawyer->user_id);
	// 			$new_post->assignToOrder($order->id);
	// 			UserScoresHistory::post();
	// 		} catch (Exception $ex) {
	// 			Log::error($ex);
	// 			return $this->makeView(
	// 					'errors.503',
	// 					'咨询律师失败，请稍后再试。',
	// 					503
	// 			);
	// 		}
	// 		return $this->makeView(
	// 				'general.201',
	// 				$new_post->toArray(),
	// 				201
	// 		);
	// 	} else {
	// 		$this->makeView( 'pay.question.create' );
	// 	}
	// }
	
	/*
	 * 全部咨询列表
	 */
	public function all(){
		$questionArr = $this->getQuestionList(null);
		return $this->makeView('center.customer.order.all',$questionArr);
		
	}
	/*
	 * 获取咨询列表
	 */
	public function getQuestionList($status){

		$questionsQuery = Post::leftJoin('post_order', 'post_order.post_id', '=', 'posts.id')
			->leftJoin('order', 'post_order.order_id', '=', 'order.id')
			->select(
				'posts.id',
				'posts.type',
				'posts.title',
				'posts.content',
				'posts.status',
				'posts.post_category',
				'posts.created_at',
				'posts.updated_at',
				'order.order_no')
			->whereIn('posts.type',array(POST::TYPE_PAY_TEXT, POST::TYPE_PAY_PHONE, POST::TYPE_PAY_COMPANY))
			->where('posts.creator_id', Auth::user()->id)
			->orderBy('updated_at', 'DESC')
			->groupBy('posts.id');
		if (!is_null($status)) {
			$questionsQuery->where('posts.status', $status);
		}
		$questions = $questionsQuery->get();
		foreach($questions as $question){
			if($question->type == Post::TYPE_PAY_PHONE && $question->status == Post::STATUS_REPLIED){
				$question['lawyer_phone'] = $question->getLawyerPhone();
			}
			$question['type'] = $question->getType();
			$question['status_code'] = $question->status;
			$question['status'] = $question->getStatus();
			$question['post_category'] = $question->getPostCatKey();
		}
		$questionArr = $questions->toArray();
		return $questionArr;
		
	}
	
	/*
	 * 待付款订单（咨询）
	 */
	public function waitPay(){
		$questions = $this->getQuestionList(Post::STATUS_WAIT_PAY);
		return $this->makeView('center.customer.order.waitpay',$questions);
	}
	
	/*
	 * 待受理（咨询）
	 */
	public function questionNew() {
		$questions = $this->getQuestionList(Post::STATUS_NEW);
		return $this->makeView('center.customer.order.new', $questions);
	}
	
	/**
	 * 罗列“已被受理”的问题
	 */
	public function questionReplied() {
		$questions = $this->getQuestionList(Post::STATUS_REPLIED);
		return $this->makeView('center.customer.order.replied', $questions);
	}
	
	/**
	 * 罗列“待评价”的问题
	 */
	public function waitforEvaluation() {
		$questions = $this->getQuestionList(Post::STATUS_WAIT_FOR_EVALUATION);
		return $this->makeView('center.customer.order.waitforconfirmation', $questions);
	}
	
	/**
	 * 罗列“已完成”的问题
	 */
	public function questionComplete() {
		$questions = $this->getQuestionList(Post::STATUS_COMPLETE);
		return $this->makeView('center.customer.order.complete', $questions);
	}
	
	/**
	 * 罗列“已取消”的问题
	 */
	public function questionCancelled() {
		$questions = $this->getQuestionList(Post::STATUS_CANCELLED);
		return $this->makeView('center.customer.order.cancelled', $questions);
	}
	
	/**
	 * 罗列“已被拒绝”的问题
	 */
	public function questionRefused() {
		$questions = $this->getQuestionList(Post::STATUS_REFUSED);
		return $this->makeView('center.customer.order.refused', $questions);
	}

	/**
	 * 查看咨询订单的详情
	 * @param $id
	 */
	public function view($id){
		/**
		 * 如果type有值,则代表id对应的是order_id,否则代表post_id
		 */
		$type = \Illuminate\Support\Facades\Input::get('type', null);
		if($type == 1){
			//基于order表单order_type字段
			$data = $this->orderService->getOrderById($id);
			if(!empty($data)){
				$data = $data->toArray();
				$data['price'] = !empty($data['price']) ? (int)$data['price'] : 0;
				$data['type'] = '打赏';
				unset($data['order_type']);
			}
		}else {
			//以前的订单,只能查询post相关的,一切都是基于post
			$question = Post::find($id);
			if (!is_a($question, 'Post')) {
				return $this->makeView('errors.404', '该订单不存在', 404);
			}
			$order = $question->getOrder($id);
			$data = [];
			if ($question->type == Post::TYPE_PAY_PHONE && $question->status == Post::STATUS_REPLIED) {
				$data ['lawyer_phone'] = $question->getLawyerPhone();
			}
			$questionArr = $question->toArray();
			$data ['post_id'] = $id;
			$data ['type'] = $question->getType();
			$data ['post_category'] = $question->getPostCatKey();
			$data ['postAttachs'] = $question->postAttach->toArray();
			$data ['price'] = round($order->price);
			$data ['order_no'] = $order->order_no;
			$data ['status_code'] = $question->status;
			$data ['status'] = $question->getStatus();
			$data ['title'] = $question->title;
			$data ['content'] = $question->content;
			$data ['updated_at'] = $questionArr['updated_at'];
			$data ['created_at'] = $questionArr['created_at'];
			$data ['lawyer'] = $question->getLawyerName();
			if ($data ['lawyer']) {
				$data ['lawyer']['avatar'] = UtilsHelper::getImage($data ['lawyer']['avatar'], 'img/df.png');
			}

		}
		if(!empty($data)){
			//余额
			$money = Wallet::getMoney();
			$data['money'] = $money;
		}

		return $this->makeView('center.customer.order.view', $data);
	}
	
	/**
	 * 查看订单的详情
	 */
	public function viewOrder($id){
		$order = Order::find($id);
		if (!is_a($order, 'Order')) {
			return $this->makeView('errors.404','该订单不存在', 404);
		}
		$data = $order->toArray();
		return $this->makeView('center.customer.order.view', $data);
	}

	public function toPay($id){
		/**
		 * 如果type有值,则代表id对应的是order_id,否则代表post_id
		 */
		$type = \Illuminate\Support\Facades\Input::get('type', null);
		if($type == 1){
			//基于order表单order_type字段
			$data = $this->orderService->getOrderById($id);
			if(!empty($data)){
				$data = $data->toArray();
				$data['price'] = !empty($data['price']) ? (int)$data['price'] : 0;
				$data['type'] = '打赏';
				$data ['post_id'] = $id;
				unset($data['order_type']);
			}
		}else {
			//以前的订单,只能查询post相关的,一切都是基于post
			$question = Post::find($id);
			if (!is_a($question, 'Post')) {
				return $this->makeView('errors.404', '该订单不存在', 404);
			}
			$order = $question->getOrder($id);
			$data = [];
			if ($question->type == Post::TYPE_PAY_PHONE && $question->status == Post::STATUS_REPLIED) {
				$data ['lawyer_phone'] = $question->getLawyerPhone();
			}
			$questionArr = $question->toArray();
			$data ['post_id'] = $id;
			$data ['type'] = $question->getType();
			$data ['post_category'] = $question->getPostCatKey();
			$data ['postAttachs'] = $question->postAttach->toArray();
			$data ['price'] = round($order->price);
			$data ['order_no'] = $order->order_no;
			$data ['status_code'] = $question->status;
			$data ['status'] = $question->getStatus();
			$data ['title'] = $question->title;
			$data ['content'] = $question->content;
			$data ['updated_at'] = $questionArr['updated_at'];
			$data ['created_at'] = $questionArr['created_at'];
			$data ['lawyer'] = $question->getLawyerName();
			if ($data ['lawyer']) {
				$data ['lawyer']['avatar'] = UtilsHelper::getImage($data ['lawyer']['avatar'], 'img/df.png');
			}

		}
		if(!empty($data)){
			//余额
			$money = Wallet::getMoney();
			$data['money'] = $money;
		}
		return $this->makeView('center.customer.question_order.pay', $data);
	}

	
	/**
	 protected function getStatusText($status)
	 {
	 $text = "";
	 switch($status) {
	 case Order::STATE_INIT:
	 $text = '待付款';
	 break;
	 case Order::STATE_CANCEL:
	 $text = '取消';
	 break;
	 case Order::STATE_PAID:
	 $text = '已付款';
	 break;
	 case Order::STATE_DONE:
	 $text = '完成';
	 break;
	 }
	 return $text;
	 }
	
	 protected function preprocessData($data)
	 {
	 foreach($data as $key => &$item) {
	 $item['order_status'] = $this->getStatusText($item['order_status']);
	 }
	 return $data;
	 }
	
	 //全部订单
	 public function index()
	 {
	 try{
	 $data = Order::allOrder();
	 $data = $this->getStubOrders();
	 $data = $this->preprocessData($data);
	 return $this->makeView('order.index', $data);
	 }catch(Exception $ex){
	 return $this->makeView('errors.503','服务器暂时无法响应，请稍后再试',503);
	 }
	 }
	
	 //待付款订单
	 public function waitPayOrder()
	 {
	 try{
	 $data = Order::waitPayOrder();
	 $data = $this->getStubOrders(Order::STATE_INIT);
	 $data = $this->preprocessData($data);
	 return $this->makeView('order.index', $data);
	 }catch (Exception $ex) {
	 Log::error($ex);
	 return $this->makeView('errors.503','服务器暂时无法响应，请稍后再试',503);
	 }
	 }
	
	 //待评价订单
	 public function waitEvaluationOrder()
	 {
	 try{
	 $data = Order::waitEvaluationOrder();
	 $data = $this->getStubOrders(Order::STATE_PAID);
	 $data = $this->preprocessData($data);
	 return $this->makeView('order.index', $data);
	 }catch(Exception $ex){
	 Log::error($ex);
	 return $this->makeView('errors.503','服务器暂时无法响应，请稍后再试',503);
	 }
	 }
	
	 //已完成订单
	 public function completeOrder()
	 {
		 try{
			 $data = Order::completeOrder();
			 $data = $this->getStubOrders(Order::STATE_DONE);
			 $data = $this->preprocessData($data);
			 return $this->makeView('order.index', $data);
			 }catch(Exception $ex){
			 Log::error($ex);
			 return $this->makeView('errors.503','服务器暂时无法响应，请稍后再试',503);
		 }
	 }
	 
	 
	public function detail($order_id)
	{
		$orderArr = $this->getStubOrders(null, $order_id);
		return $this->makeView('order.item', $orderArr);

		try{
			$order = App::make('Order')->find($order_id);
			$datas = array();
			$order_id = $order->id;
			$order_items = App::make('OrderItem')->where('order_id', $order_id)->get();
			$datas['order_id'] = $order->id;
			$datas['order_no'] = $order->order_no;
			$datas['order_status'] =  $order->workflow()->node->name;
			$datas['created_at'] = $order->created_at;
			$datas['total_price'] = round($order->price);
			$datas['qty'] = $order_items->count();
			$datas['memo'] = $order->memo;
			$datas['phone'] = $order->phone;

			$datas['order_items'] = array();
			foreach($order_items AS $order_item)
			{
				$product = $order_item->product;
				if($product)
				{
						$datas['order_items'][$product->id] = array(
								'product_img' => $product->thumb,	
								'product_name' => $product->name,	
								'product_price' => round($order_item->price),	
								'product_id' => $product->id,	
								'product_qty' => $order_item->qty,	
								'subtotal' => $order_item->qty*$order_item->price,	
						);
				}
			}
		}catch (Exception $ex) {
			Log::error($ex);
    		return $this->makeView('errors.503','服务器暂时无法响应，请稍后再试',503);
    	}
		return	$this->makeView('order.item', $datas);
	}

	//删除订单
	 
	public function remove($order_id){
		$order = Order::find($order_id);
		if(!$order){
			return $this->makeView('errors.400','该订单不存在',400);
		}
		if($order->user_id != Auth::user()->id){
			return $this->makeView('errors.400','你没有权限删除该订单',400);
		}
		try{
			$order->delete();
		}catch (Exception $ex) {
			Log::error($ex);
    		return $this->makeView('errors.503','服务器暂时无法响应，请稍后再试',503);
    	}
    	return $this->makeView('general.200','删除成功',200);
	}
	
	
	 */
}
